<template>
  <div>
      <!-- 运动统计卡片 -->
    <el-row :gutter="20" class="weight-stats-cards">
      <el-col :span="8">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-card-content">
            <div class="stats-card-value">{{ sportStats.wxSetps || 0 }}</div>
            <div class="stats-card-label">微信运动步数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-card-content">
            <div class="stats-card-value">{{ sportStats.time || '0' }}</div>
            <div class="stats-card-label">运动时长 (h)</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-card-content">
            <div class="stats-card-value">{{ sportStats.kalorie || '0' }}</div>
            <div class="stats-card-label">消耗热量 (kcal)</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  <div class="sport-history">
    <el-card class="box-card">
      <CapsuleTabs ref="tabItems" :tabs="tabs" @tab-change="handleTabChange">
        <template #tab-0>
          <transition name="fade" mode="out-in">
            <div v-if="tdList.length" class="sport-history-list">
              <div class="motion-list">
                <!-- 今日运动记录 - 两列显示 -->
                <div class="motion-grid">
                  <div v-for="(item, index) in tdList" :key="item.id" class="motion-item">
                  <el-card
                    class="card-height"
                    :style="{
                      background: `url(${getSportIcon(item.sportId)}) no-repeat right 20px bottom 20px`,
                      backgroundSize: '60px',
                      border: 'none'
                    }"
                  >
                    <div class="card-overlay" :style="{ backgroundColor: getSportBgClass(item.sportId) || mainColor }"                      >
                      <!-- 运动类型与日期 -->
                      <div class="sport-header">
                        <div class="sport-name">{{ item.sportName }}</div>
                        <div class="create-time"><i class="el-icon-time"></i>{{ item.createTime }}</div>
                      </div>

                      <!-- 运动详情 -->
                      <div class="sport-stats">
                        <el-statistic
                          class="stat-item"
                          title="运动时长"
                          :value="item.time * item.num"
                          :precision="0"
                          :value-style="{ fontSize: '24px', color: '#fff' }"
                          :title-style="{ fontSize: '14px', color: 'rgba(255,255,255,0.8)' }"
                        >
                          <template #suffix><span class="unit-text">分钟</span></template>
                        </el-statistic>
                        <el-statistic
                          class="stat-item"
                          title="消耗热量"
                          :value="item.calorie * item.num"
                          :precision="0"
                          :value-style="{ fontSize: '24px', color: '#fff' }"
                          :title-style="{ fontSize: '14px', color: 'rgba(255,255,255,0.8)' }"
                        >
                          <template #suffix><span class="unit-text">千卡</span></template>
                        </el-statistic>
                      </div>
                    </div>
                  </el-card>
                </div>
                </div>
              </div>
            </div>
            <!-- 无运动记录时展示空状态 -->
            <div v-else class="empty-state">
              <el-empty :image-size="100"></el-empty>
            </div>
          </transition>
        </template>
        <template #tab-1>
          <transition name="fade" mode="out-in">
            <div v-if="ydList.length" class="sport-history-list">
              <div class="motion-list">
                <!-- 历史运动记录 - 两列显示 -->
                <div class="motion-grid">
                  <div v-for="(item, index) in ydList" :key="item.id" class="motion-item">
                  <el-card
                  class="card-height"
                    :style="{
                      background: `url(${getSportIcon(item.sportId)}) no-repeat right 20px bottom 20px`,
                      backgroundSize: '60px',
                      border: 'none'
                    }"
                  >
                    <div class="card-overlay" :style="{ backgroundColor: getSportBgClass(item.sportId) || mainColor }"                      >
                      <!-- 运动类型与日期 -->
                      <div class="sport-header">
                        <div class="sport-name">{{ item.sportName }}</div>
                        <div class="create-time"><i class="el-icon-time"></i>{{ item.createTime }}</div>
                      </div>

                      <!-- 运动详情 -->
                      <div class="sport-stats">
                        <el-statistic
                          class="stat-item"
                          title="运动时长"
                          :value="item.time * item.num"
                          :precision="0"
                          :value-style="{ fontSize: '24px', color: '#fff' }"
                          :title-style="{ fontSize: '14px', color: 'rgba(255,255,255,0.8)' }"
                        >
                          <template #suffix><span class="unit-text">分钟</span></template>
                        </el-statistic>
                        <el-statistic
                          class="stat-item"
                          title="消耗热量"
                          :value="item.calorie * item.num"
                          :precision="0"
                          :value-style="{ fontSize: '24px', color: '#fff' }"
                          :title-style="{ fontSize: '14px', color: 'rgba(255,255,255,0.8)' }"
                        >
                          <template #suffix><span class="unit-text">千卡</span></template>
                        </el-statistic>
                      </div>
                    </div>
                  </el-card>
                </div>
                </div>
                <!-- 加载更多按钮 -->
                <div v-if="ydList.length > 0" class="load-more">
                  <el-button
                    type="text"
                    :disabled="!hasMore"
                    @click="loadMore"
                  >
                    {{ hasMore ? '加载更多' : '没有更多数据了' }}
                  </el-button>
                </div>
              </div>
            </div>
            <!-- 无运动记录时展示空状态 -->
            <div v-else class="empty-state">
              <el-empty :image-size="100"></el-empty>
            </div>
          </transition>
        </template>
      </CapsuleTabs>
    </el-card>
  </div> 
  </div>
</template>

<script>
import { listAllSport } from '@/api/miniapp/wxSport'
import { listHistory, sportRecordList} from "@/api/miniapp/wxSportHistory";
import CapsuleTabs from '@/components/CapsuleTabs';
import moment from "moment";
export default {
  components: {
        CapsuleTabs
  },
  props: {
    userId: {
      type: Number,
      default: 0
    },
    openId: {
      type: String,
      default: ''
    },
    queryDate: {
      type: Date,
      default: new Date()
    }
  },
  data() {

    return {
      // 用户信息
      userInfo:{},
      // 运动记录列表
      ydList: [],
      // 今日运动记录列表
      tdList: [],
      // 运动类型列表
      sportList: [],
      // 标签页索引
      tabIndex: '0',
      // 分页参数
      pageNum: 1,
	    pageSize: 6,
      total: 0,
      loading: false,
      hasMore: true,
      // 默认背景色
      mainColor: 'rgba(90, 126, 215, 0.8)',
      tabs: [
        { label: '今日运动记录' },
        { label: '历史运动记录' }
      ],
      sportStats:{
        time: 0,
        calorie: 0,
        wxSetps: '/'
      }
    }
  },

  mounted() {
    this.init()
  },
  watch: {
    userId() {  
      this.getHistoryList()
      this.getSportRecordList()
    },
    queryDate() {
      console.log('queryDate: ', this.queryDate);
      this.getSportRecordList()
    }
  },  
  methods: {
    handleTabChange(index) {
      //console.log('切换到标签:', index);
    },
    // 加载更多数据
    loadMore() {
      this.pageNum++;
      this.getHistoryList(true);
    },
      // 初始化数据
    init() {
        //查询今日运动记录
        this.getSportRecordList()
        //查询运动列表
        this.getSportList()
        //查询历史运动记录
        this.getHistoryList()
    },
    getHistoryList(isLoadMore = false){
      const params={
        userId:this.userId,
        openId: this.openId,
        pageNum: this.pageNum,
				pageSize: this.pageSize
      }
      listHistory(params).then(response => {
        const list = response.data.list || [];
        this.hasMore = list.length >= this.pageSize;
        if (isLoadMore) {
          this.ydList = [...this.ydList, ...list];
        } else {
          this.ydList = list;
        }
      })
    },
    // 获取今日运动记录
    getSportRecordList() {
      console.log(this.queryDate)
      const params = {
        userId: this.userId,
        openId: this.openId,
        date: moment(this.queryDate).format("YYYY-MM-DD")
      }

      console.log('queryDa11111te: ', this.queryDate);
      sportRecordList(params).then(response => {
        this.tdList = response.data || []

        // 使用reduce一次性计算总和
        const { totalCalories, totalTime } = response.data.reduce(
            (acc, item) => {
                // 累加卡路里 (注意calorie是字符串，需要转换为数字)
                acc.totalCalories += Number(item.calorie) * item.num;
                // 累加运动时间
                acc.totalTime += item.time * item.num;
                return acc;
            }, { totalCalories: 0, totalTime: 0 }
        );
        this.sportStats = {
          wxSetps: 0,
          time: totalTime,
          kalorie: totalCalories
        };
      })
    },

    // 获取运动类型列表
    getSportList() {
      const params = {}
      listAllSport(params).then(response => {
         this.sportList = response.data || []
      })
    },

    // 获取运动图标
    getSportIcon(sportId) {
      const sport = this.sportList.find(item => item.id === sportId)
      try {
        return sport?.icon
          ? require(`@/assets/sport/${sport.icon}`)
          : require(`@/assets/sport/icon-sport-default.png`)
      } catch (e) {
        console.error('图标加载失败', e)
        return require(`@/assets/sport/icon-sport-default.png`)
      }
    },

    // 获取运动背景色
    getSportBgClass(sportId) {
      const sport = this.sportList.find(item => item.id === sportId)
      if (!sport?.bgColor) return this.mainColor

      if (sport.bgColor.startsWith('rgb')) {
        const match = sport.bgColor.match(/rgb\(([^)]+)\)/) || sport.bgColor.match(/rgba\(([^)]+)\)/)
        if (match?.[1]) {
          const [r, g, b] = match[1].split(',').map(v => v.trim())
          return `rgba(${r}, ${g}, ${b}, 0.8)`
        }
      }
      return sport.bgColor
    },

    // 切换标签页
    handleTabChange(tab) {
      this.tabIndex = tab.name
      // 可添加历史记录加载逻辑
    },
  }
}
</script>
<style lang="scss" scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.card-header {
  padding: 10px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.sport-history-list{
  max-height: 500px;
  overflow-y: auto;
}

.motion-list{
  max-height: 500px;
  overflow-y: auto;
}

.motion-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 5px;
  padding: 0 10px;
}

.motion-item {
  width: 100%;
  padding: 5px;
}

.el-card {
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}

.card-height{
    min-height: 140px;
}

.card-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  padding: 20px;
  border-radius: 8px;
  color: #fff;
}

.sport-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  width: 100%;
}

.sport-name {
  font-size: 18px;
  font-weight: bold;
  color: #fff;
  text-align: left;
}

.create-time {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  text-align: right;
}

.sport-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.stat-item {
  flex: 1;
  text-align: center;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

::v-deep .el-statistic {
  text-align: center;
  margin: 0 10px;
}

::v-deep .el-statistic__content {
  justify-content: center;
}

::v-deep .el-date-editor {
  background-color: rgba(255, 255, 255, 0.2);
  border: none;
}

::v-deep .el-date-editor .el-input__inner {
  color: #fff;
  border: none;
  background: transparent;
}

::v-deep .el-tabs__nav {
  margin-bottom: 0;
}

.unit-text {
  font-size: 12px;
  color: #ffffff;
}





/* 体重统计卡片样式 */
.weight-stats-cards {
  margin-bottom: 20px;
}

.stats-card {
  height: auto;
}

.stats-card-content {
  text-align: center;
  padding: 10px 0;
}

.stats-card-value {
  font-size: 24px;
  font-weight: 600;
  color: #409EFF;
  margin-bottom: 5px;
}

.stats-card-label {
  font-size: 12px;
  color: #909399;
}
</style>
